package com.qcby.admin.controller;


import com.qcby.admin.model.SysMenu;
import com.qcby.admin.service.SysMenuService;
import com.qcby.admin.utils.SystemConverter;
import com.qcby.admin.vo.MenuTreeVo;
import com.qcby.admin.vo.MenuVo;
import com.qcby.framwork.utils.BeanCopyUtils;
import com.qcby.framwork.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 菜单权限表 前端控制器
 * </p>
 *
 * @author admin
 * @since 2024-09-19
 */
@RestController
@RequestMapping("/system/menu")
public class SysMenuController {
    @Autowired
    private SysMenuService sysMenuService;
    /**
     * 获取菜单列表
     */
    @GetMapping("/list")
    public ResponseResult list(SysMenu menu) {
        List<SysMenu> menus = sysMenuService.selectMenuList(menu);
        List<MenuVo> menuVos = BeanCopyUtils.copyBeanList(menus, MenuVo.class);
        return ResponseResult.okResult(menuVos);
    }
    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public ResponseResult treeselect() {
        //复用之前的selectMenuList方法。方法需要参数，参数可以用来进行条件查询，而这个方法不需要条件，所以直接new Menu()传入
        List<SysMenu> menus = sysMenuService.selectMenuList(new SysMenu());
        List<MenuTreeVo> options =  SystemConverter.buildMenuSelectTree(menus);
        return ResponseResult.okResult(options);
    }

    /*加载对应角色菜单列表树*/
    @GetMapping("/roleMenuTreeselect/{roleId}")
    public ResponseResult roleMenuTreeselect(@PathVariable Long roleId){
        //List<RoleMenuTreeVo> result=menuService.getRoleMenuTreeselect(roleId);
        HashMap<String, Object> data = sysMenuService.buildRoleMenuTree(roleId);

        return ResponseResult.okResult(data);
    }
    @PostMapping
    public ResponseResult add(@RequestBody SysMenu menu)
    {
        sysMenuService.save(menu);
        return ResponseResult.okResult();
    }


    /**
     * 根据菜单编号获取详细信息
     */
    @GetMapping(value = "/{menuId}")
    public ResponseResult getInfo(@PathVariable Long menuId)
    {
        return ResponseResult.okResult(sysMenuService.getById(menuId));
    }

    /**
     * 修改菜单
     */
    @PutMapping
    public ResponseResult edit(@RequestBody SysMenu menu) {
        if (menu.getId().equals(menu.getParentId())) {
            return ResponseResult.errorResult(500,"修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        sysMenuService.updateById(menu);
        return ResponseResult.okResult();
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{menuId}")
    public ResponseResult remove(@PathVariable("menuId") Long menuId) {
        if (sysMenuService.hasChild(menuId)) {
            return ResponseResult.errorResult(500,"存在子菜单不允许删除");
        }
        sysMenuService.removeById(menuId);
        return ResponseResult.okResult();
    }
}

